package site.wetsion.employ.server.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import site.wetsion.employ.server.pojo.Company;
import site.wetsion.employ.server.pojo.Location;
import site.wetsion.employ.server.service.JobService;
import site.wetsion.employ.server.service.UserService;
import site.wetsion.employ.server.util.MD5Util;
import site.wetsion.employ.server.util.Page;
import site.wetsion.employ.server.util.Result;
import site.wetsion.employ.server.util.SendCode;
import site.wetsion.employ.server.vo.CompanyListVo;
import site.wetsion.employ.server.vo.LocationVo;
/**
 * 工具控制类，例如：
 * 发送验证码、ajax上传图片
 * @author Wetsion
 *
 */
@Controller
public class UtilController {
	
	private final static Logger log = LoggerFactory.getLogger(UtilController.class);

	private final static String UPLOAD_PATH = "F:\\image\\";
	
	@Autowired
	private UserService userService;

	@Autowired
	private JobService jobService;
	
	@ResponseBody
	@PostMapping("email/sendcode")
	public Result sendcode(String email, HttpSession session){
		boolean ck = userService.checkRegister(email);
		if(ck){
			return new Result(500, "邮箱已注册！");
		}
		String str="0123456789qwertyuiopasdfghjklzxcvbnm";
		StringBuilder builder=new StringBuilder();
		for(int i=0;i<6;i++){
			int rand = (int) (Math.random() * str.length());
			builder.append(str.charAt(rand));
		}
		String code = builder.toString();
		session.setAttribute("emailcode", code);
		try {
			SendCode.sendCodeByEmail(code, email);
			return new Result(200, "邮件发送成功，查看邮件获取验证码");
		} catch (MessagingException e) {
			log.error("邮件发送失败", e);
			return new Result(503, "邮件发送失败，请稍后再试");
		}
	}
	
	/**
	 * ajax上传图片
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/admin/uploadImage/{type}")
	public Result uploadImage(MultipartHttpServletRequest request,@PathVariable int type){
		System.out.println("test");
		String storePath = "";
		if(type == 0){
			storePath = UPLOAD_PATH + "companylogo\\";
		}
		if(type == 1){
			storePath = UPLOAD_PATH + "productimage\\";
		}
		if(type == 2){
			storePath = UPLOAD_PATH + "checkfile\\";
		}
		Iterator<String> iter = request.getFileNames();
		String subfix=null;
		String md5name=null;
		while(iter.hasNext()){
			String ite = iter.next();
			MultipartFile file = request.getFile(ite);
			
			String filename = file.getOriginalFilename();
			System.out.println(filename);
//			String path = request.getRealPath("/image");
//		System.out.println(path);
			String imagename = filename.substring(0, filename.lastIndexOf("."));
			subfix = filename.substring(filename.lastIndexOf("."));
			md5name = MD5Util.getMD5String(imagename);
			InputStream inputStream;
			try {
				System.out.println(md5name+subfix);
				inputStream = file.getInputStream();
				FileOutputStream fileOutputStream=new FileOutputStream(storePath+md5name+subfix);
				byte[] buf=new byte[1024];
				int length=0;
				while((length=inputStream.read(buf))!=-1){
					fileOutputStream.write(buf, 0, length);
				}
				inputStream.close();
				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				return new Result(804, "上传失败");
			} catch (IOException e) {
				return new Result(804, "上传失败");
			}
		}
		return new Result(800, md5name+subfix);
	}
	
	/**
	 * 根据用户输入的关键词自动显示城市列表
	 * @param keyword
	 * @return
	 */
	@ResponseBody
	@GetMapping("location/autoshow")
	public LocationVo autoshow(String keyword){
		LocationVo vo = new LocationVo();
		List<Location> locationList = jobService.searchLocationByKeyword(keyword);
		vo.setLocationList(locationList);
		return vo;
	}
	
}
